package org.huamoxi.config;

import org.huamoxi.service.impl.SecurityUserDetailsImpl;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.AccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * oauth2 的配置类
 */
@Configuration
@EnableAuthorizationServer // 开启oauth2 认证
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    // WebSecurityConfig 中注册
    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    AuthenticationManager authenticationManager;

    // JwtTokenConfig 中注册
    @Resource(name = "jwtTokenStore")
    TokenStore jwtTokenStore;
    @Resource(name = "jwtAccessTokenConverter")
    AccessTokenConverter accessTokenConverter;

    // DataSourceConfig 中注册
    @Resource(name = "oauth2DataSource")
    DataSource dataSource;

    // UserDetailsService
    SecurityUserDetailsImpl securityUserDetails;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.allowFormAuthenticationForClients()
                .passwordEncoder(passwordEncoder);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints){
        endpoints
                .accessTokenConverter(accessTokenConverter) // jwt生成access_token
                .authenticationManager(authenticationManager) // password 密码认证所需配置
                .tokenStore(jwtTokenStore) // 采用jwt的token管理方式
                .userDetailsService(securityUserDetails) // refresh 刷新令牌时的认证
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .reuseRefreshTokens(false)
        ;
    }
}
